package com.example.routeplansystem.controller;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.example.routeplansystem.anotation.UserPermissionConf;
import com.example.routeplansystem.define.FileEnum;
import com.example.routeplansystem.exception.ServiceException;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Author lucong
 * @Date 2022/8/18
 * @Description
 */
@RequestMapping("file")
@Controller
@Api(tags = "文件模块")
@Validated
@UserPermissionConf
public class FileController {


    @Autowired
    private ResourceLoader resourceLoader;

    //通用文件模板下载：
    @GetMapping("/{path}/download")
    @ApiOperation("下载文件模板")
    public org.springframework.http.ResponseEntity<byte[]> downloadFileTemplate(@PathVariable("path") String path,
                                                                                HttpSession session) throws IOException {
        FileEnum fileEnum = FileEnum.getFile(path);
        if (fileEnum == null) {
            throw new ServiceException("文件不存在!!!");
        }
        String fileName = fileEnum.getFileName();
        //1.获取ServletContext对象：
        ServletContext servletContext = session.getServletContext();
        //2.获取服务器中文件的真实路径：
        Resource resource = resourceLoader.getResource("classpath:static\\" + fileName);
        //3.创建输入流：
        InputStream inputStream = resource.getInputStream();
        //4.创建字节数组：
        byte[] bytes = new byte[inputStream.available()];
        //5.将流读到字节数组中：
        inputStream.read(bytes);
        //6.创建HttpHeader对象设置相应头信息：
        HttpHeaders headers = new HttpHeaders();
        //7.设置下载方式以及下载文件的名称：
        headers.setContentDisposition(ContentDisposition.builder("attachment").filename(URLEncoder.encode(fileName,
                "UTF-8")).build());
        //8.设置相应状态码：
        HttpStatus statusCode = HttpStatus.OK;
        //9.创建ResponseEntity对象：
        org.springframework.http.ResponseEntity<byte[]> responseEntity = new org.springframework.http.ResponseEntity<>(bytes, headers, statusCode);
        //10.关闭流：
        inputStream.close();
        return responseEntity;
    }

}
